/**
 * Created by zhulizhe on 2017/8/16.
 */
import React, {Component} from 'react';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    Navigator,
    FlatList,
    Animated,
    Dimensions,
    RefreshControl,
    ActivityIndicator,
    Platform,
    ViewPagerAndroid
} from 'react-native';
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import {PriceLabel} from '../home/ShoppingCart'
import QuickPay from '../home/QuickPay'
import {SignOrder} from './OrderNet'
import OrderStore from './OrderListStore'
import ScrollableTabView from 'react-native-scrollable-tab-view';
import { ActionSheetCustom as ActionSheet } from 'react-native-actionsheet'

let ScreenHeight = Dimensions.get('window').height;
let ScreenWidth = Dimensions.get('window').width;

const actionParam = {orderId:0,
                     status:'',
                     totalPayRmb:0};
const CANCEL_INDEX = 0;
const DESTRUCTIVE_INDEX = 1;
const options = [ '取消', '确定'];
const title = '您确定签收该订单吗？';

const OrderSelectView = React.createClass({
    propType: {
        goToPage: React.PropTypes.func,
        activeTab: React.PropTypes.number,
        tabs: React.PropTypes.array,
        tabStyle: View.propTypes.style,
        underlineStyle: View.propTypes.style,
    },
    render(){
        const backS = {
            flexDirection:'row',
            justifyContent:'space-between',
            height:35,
            alignItems:'center'
        };
        const btnS = {
            height:35,
            width:ScreenWidth/4,
            justifyContent:'center',
            alignItems:'center'
        };
        const tabUnderlineStyle = {
            position: 'absolute',
            width: ScreenWidth/4,
            height: 3,
            backgroundColor: '#4dc0ff',
            bottom: 0,
            borderRadius:1.5,
        };
        const left = this.props.scrollValue.interpolate({
            inputRange: [0, 1, ], outputRange: [0, ScreenWidth/4, ],
        });
        return <View style={backS}>
            {this.props.tabs.map((tab, i)=> {
                let textColor = this.props.activeTab==i ? '#4dc0ff' : '#333333';
                return <TouchableOpacity style={btnS}
                                         activeOpacity={1}
                                         onPress={()=>{
                                             this.props.goToPage(i)
                                         }}
                                         key={tab}>
                    <Text style={{color:textColor}}>{tab}</Text>
                </TouchableOpacity>
            })}
            <Animated.View style={[tabUnderlineStyle, { left, }]} />
        </View>
    }
});

export class OrderProductCell extends Component {
    render(){
        let {currentPrice,
             name,
             volume,
             selectCount,
             productImage} = this.props.product;
        return <View>
            <View style={OrderCellStyle.imageViewS}>
                <Image style={OrderCellStyle.imageS} source={{uri:productImage}}/>
                <View style={OrderCellStyle.contentS}>
                    <View>
                        <Text style={{color:'rgba(51,51,51,1)'}}>{name}</Text>
                        <Text style={{fontSize:12.5,color:'rgba(119,119,119,1)'}}>{volume}</Text>
                    </View>
                    <Text style={{fontSize:14.5,color:'rgba(51,51,51,1)'}}>
                        <Text style={{fontSize:10.5}}>¥</Text>{currentPrice/100+''}
                        <Text style={{fontSize:12.5}}> x </Text>{selectCount+''}</Text>
                </View>
            </View>
            <View style={OrderCellStyle.lineS}/>
        </View>
    }
}

@observer
class OrderCell extends Component {
    actionParamAssign(param){
        actionParam.orderId = param.orderId;
        actionParam.status = param.status;
        actionParam.totalPayRmb = param.totalPayRmb;
    }
    render(){
        let order = this.props.data.item;
        let rightText = order.status=='待付款' ? '去支付' : order.status=='待收货'?'签收':'评价';
        let param = {orderId:order.orderId,
                     orderNo:order.orderNo,
                     status:order.status,
                     totalPayRmb:order.totalPayRmb};
        return <TouchableOpacity style={{backgroundColor:'rgba(241,241,243,1)'}}
                                 activeOpacity={1}
                                 onPress={()=>{this.props.detailPress(param)}}>
            <View style={OrderCellStyle.topViewS}>
                <View style={{flexDirection:'row',height:15,alignItems:'center'}}>
                    <Image style={{marginLeft:12,height:15,width:15}} source={require('../../asserts/order/tab_icon_water_station_s.png')}/>
                    <Text style={{marginLeft:3,color:'rgba(119,119,119,1)'}}>{order.shopName}</Text>
                </View>
                <Text style={{marginRight:12,color:'rgba(77,192,255,1)'}}>{order.status}</Text>
            </View>
            <View style={OrderCellStyle.lineS}/>
            {order.productItemModels.map((product,index)=>{
                return <OrderProductCell product={product} key={index}/>
            })}
            <View style={OrderCellStyle.backViewS}>
                <Text style={{marginRight:12,fontSize:12.5,color:'rgba(119,119,119,1)'}}>共 {order.totalCount+''} 件商品，实付款:
                <Text style={{fontSize:14.5,color:'#ff2d2d'}}><Text style={{fontSize:10.5}}> ¥</Text>{order.totalPayRmb/100+''}</Text></Text>
            </View>
            <View style={OrderCellStyle.lineS}/>
            <View style={OrderCellStyle.backViewS}>
                <TouchableOpacity style={OrderCellStyle.opeBtnS}
                                  onPress={()=>{this.actionParamAssign(param);
                                                if(order.status=='待付款' || order.status=='待评价'){
                                                    this.props.payPraise(param)
                                                } else if (order.status=='待收货'){
                                                    this.props.leftAction()
                                                }}}>
                    <Text style={{color:'rgba(77,192,255,1)'}}>{rightText}</Text>
                </TouchableOpacity>
            </View>
            <View style={{flexDirection:'row',height:15,backgroundColor:'rgba(241,241,243,1)'}}/>
        </TouchableOpacity>
    }
}

const OrderCellStyle = {
    topViewS : {
        flexDirection: 'row',
        height:40,
        backgroundColor:'white',
        justifyContent:'space-between',
        alignItems:'center'
    },
    backViewS : {
        flexDirection:'row',
        height:40,
        backgroundColor:'white',
        justifyContent:'flex-end',
        alignItems:'center'
    },
    imageViewS : {
        flexDirection: 'row',
        height:85,
        backgroundColor:'white',
        alignItems:'center'
    },
    imageS : {
        flexDirection: 'row',
        marginLeft: 12,
        width: 65,
        height: 65,
        justifyContent: 'center',
        borderRadius: 4,
        alignSelf:'center'
    },
    contentS : {
        marginLeft:10,
        height:55,
        justifyContent:'space-between'
    },
    lineS : {
        flexDirection:'row',
        height:0.5,
        backgroundColor:'rgba(227,227,227,1)'
    },
    opeBtnS : {
        marginRight:12,
        width:70,
        height:25,
        borderRadius: 3,
        borderColor:'rgba(77,192,255,1)',
        borderWidth:0.5,
        justifyContent:'center',
        alignItems:'center'
    }
};

class OrderEmpHeader extends Component {
    render(){
        const empStyle = {
            backS : {
                height:ScreenHeight-99,
                alignItems:'center'
            },
            textS : {
                marginTop:(ScreenHeight-64)/2-80,
                fontSize:13,
                color:'rgba(119,119,119,1)'
            }
        };
        return <View style={empStyle.backS}>
            <Text style={empStyle.textS}>暂时没有相关订单</Text>
        </View>
    }
}

@observer
class OrderList extends Component {
    constructor(props){
        super(props);
        this.state = {
            loading:true,
            orderA:[]
        };
        this.pageNo=0;
    };
    componentDidMount(){
        OrderStore.refreshList(this.props.pageIndex,this.pageNo,this.props.orderStatus);
        this.loadDone()
    };
    // 详情
    goToDetail(param){
        alert(1);
        this.props.navigation.navigate('OrderDetail',{orderParam:param})
    };
    // 去支付
    payPraiseOrder(param){
        if (param.status=='待付款') {
            this.props.navigation.navigate('QuickPay', {orderNo: param.orderNo, orderId: param.orderId, totalPrice: param.totalPayRmb});
        } else if (param.status=='待评价'){
            this.props.navigation.navigate('Judge', {orderNo: param.orderNo, orderId: param.orderId});
        }

    };
    loadDone(){
        this.setState({
            loading:false
        })
    };
    _getList(){
        if (this.props.pageIndex==0) {
            return OrderStore.allList;
        } else if (this.props.pageIndex==1) {
            return OrderStore.createList;
        } else if (this.props.pageIndex==2) {
            return OrderStore.deliveryList;
        } else if (this.props.pageIndex==3) {
            return OrderStore.appraiseList;
        }
    };
    _headRefresh(){
        this.pageNo=0;
        this.setState({orderA:[]});
        OrderStore.refreshList(this.props.pageIndex,this.pageNo,this.props.orderStatus);
        this.loadDone()
    };
    _keyExtractor = (item, index) => item.id;
    _renderItem=(item)=>(<OrderCell data={item}
                                    id={item.id}
                                    detailPress={this.goToDetail.bind(this)}
                                    payPraise={this.payPraiseOrder.bind(this)}
                                    leftAction={this.props.cancelDelete}/>);
    _renderEmpty(){
        return <OrderEmpHeader />
    };
    render(){
        return <FlatList onEndReachedThreshold={1}
                         data={this._getList()}
                         keyExtractor={this._keyExtractor}
                         renderItem={this._renderItem.bind(this)}
                         ListEmptyComponent={this._renderEmpty.bind(this)}
                         onRefresh={this._headRefresh.bind(this)}
                         refreshing={this.state.loading}
                         style={{flex:1}}/>
    };
}

export default class Order extends Component{
    static navigationOptions = {
        title: '订单'
    };
    constructor(props){
        super(props);
        this.state={
            tabs:['全部', '待付款','待收货'],
            activeTab:0
        };
        this.initialIndex = 0 ;
        if(this.props.navigation.state.params){
            this.initialIndex=this.props.navigation.state.params.index||0;
        }
    }
    async cancelDeleteAction(){
        if (actionParam.status=='待收货') {
            let param = {orderId:actionParam.orderId};
            let singOrder = await SignOrder(param);
            if (singOrder=="success") {
                alert('success');
            }
            console.log('+++++++++待收货'+singOrder);
        }
    }
    render(){
        return <View style={{flex:1,backgroundColor:'rgba(241,241,243,1)'}}>
            {this._getTab()}
            <ActionSheet ref="ActionSheet"
                         title={title}
                         options={options}
                         cancelButtonIndex={CANCEL_INDEX}
                         destructiveButtonIndex={DESTRUCTIVE_INDEX}
                         onPress={()=>{this.cancelDeleteAction()}}/>
        </View>
    }
    _getTab(){
            return <ScrollableTabView initialPage={this.initialIndex}
                                      style={{height:90}}
                                      renderTabBar={()=> <OrderSelectView />}
                                      tabBarActiveTextColor='#4dc0ff'
                                      tabBarInactiveTextColor='#333333'
                                      tabBarUnderlineStyle={{backgroundColor:'#4dc0ff',height:2,width:10}}>
                <OrderList {...this.props} tabLabel="全部" pageIndex={0} orderStatus='全部' cancelDelete={()=>{this.refs.ActionSheet.show()}}/>
                <OrderList {...this.props} tabLabel="待付款" pageIndex={1} orderStatus='待付款' cancelDelete={()=>{this.refs.ActionSheet.show()}}/>
                <OrderList {...this.props} tabLabel="待收货" pageIndex={2} orderStatus='待收货' cancelDelete={()=>{this.refs.ActionSheet.show()}}/>
                <OrderList {...this.props} tabLabel="待评价" pageIndex={3} orderStatus="待评价" cancelDelete={()=>{this.refs.ActionSheet.show()}}/>
            </ScrollableTabView>
    }
}

